<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <link href="/wangeditor-5.1.23/style.css" rel="stylesheet">
    <script src="/wangeditor-5.1.23/index.js" charset="utf-8"></script>
    <style>
        body { background-color: #ffffff; }
        #editor—wrapper {
            border: 1px solid #ccc;
            z-index: 100; /* 按需定义 */
        }
        #toolbar-container { border-bottom: 1px solid #ccc; }
        #editor-container { height: 300px; }
    </style>
</head>
<body>
<div class="layuimini-container" id="app">
    <div class="layuimini-main">
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
            <legend>游戏包{{detail.id?'编辑':'添加'}}</legend>
        </fieldset>
        <form class="layui-form" action="javascript:;" >



            <div class="layui-form-item">
                <label class="layui-form-label">选择渠道</label>
                <div class="layui-input-block">
                    <select v-model="detail.game_channel_id" class="layui-select" lay-verify="required" lay-filter="game_channel_id">
                        <option value="">--请选择--</option>
                        <option v-for="item in channels" :value="item.id">{{item.name}}</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">选择母包渠道</label>
                <div class="layui-input-block">
                    <select class="layui-select" v-model="detail.pack_channel_id" lay-verify="required" lay-filter="package_channel_id">
                        <option v-if="!packagechannels || packagechannels.length === 0" value="">无渠道包</option>
                        <option v-else value="">--请选择--</option>
                        <option v-for="item in packagechannels" :key="item.id" :value="item.id">
                            {{ item.nick  }}|| {{ item.name  }}
                        </option>
                    </select>
                </div>
            </div>

            
            
            <div class="layui-form-item">
                <label class="layui-form-label">子包号</label>
                <div class="layui-input-block">
                    <input type="text" v-model="detail.sub_package_no" @input="generateChannelPackageNo" autocomplete="off" placeholder="请输入" class="layui-input">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">渠道包号</label>
                <div class="layui-input-block">
                    <input type="text" v-model="detail.package_no" readonly autocomplete="off" placeholder="自动生成" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">渠道标识符</label>
                <div class="layui-input-block">
                    <input type="text" v-model="detail.channel" lay-verify="title" autocomplete="off" placeholder="请输入" class="layui-input" >
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label">渠道配置标识</label>
                <div class="layui-input-block">
                    <input type="text" v-model="detail.channelcg"    autocomplete="off" placeholder="请输入" class="layui-input" readonly>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">渠道账号和订单标识</label>
                <div class="layui-input-block">
                    <input type="text" v-model="detail.channeltip"    autocomplete="off" placeholder="请输入" class="layui-input" >
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品配置</label>
                <div class="layui-input-block">
                    <select v-model="detail.configtype" class="layui-select" lay-filter="configtype" lay-verify="required">
                        <option value="">--请选择--</option>
                        <option v-for="item in configgroup" :value="item.type" lay-ignore>{{item.name}}</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">端版本</label>
                <div class="layui-input-block">
                    <select v-model="detail.type" class="layui-select" lay-filter="type" lay-verify="required">
                        <option value="">--请选择--</option>
                        <option v-for="item in types" :value="item.type" lay-ignore>{{item.name}}</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">包版本说明</label>
                <div class="layui-input-block">
                    <input type="text" v-model="detail.description" autocomplete="off" placeholder="请输入" class="layui-input">
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label">测试包</label>
                <div class="layui-input-block">
                    <input type="radio" name="is_test" lay-filter="is_test" value="0" title="否" :checked="!Id || detail.is_test===0">
                    <input type="radio" name="is_test" lay-filter="is_test" value="1" title="是" :checked="detail.is_test===1">
                </div>
            </div>



            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">版权文本</label>
                <input type="hidden" name="content" :value="detail.content">
                <div class="layui-input-block">
                    <div id="editor—wrapper">
                        <div id="toolbar-container"><!-- 工具栏 --></div>
                        <div id="editor-container"><!-- 编辑器 --></div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/js/common.js?v=5" charset="utf-8"></script>
<script>
    from = null;
    Id = urlParam('id')
    var configgroup = getEnum('configgroup')
    var channels = getEnum('channel')
    var packagechannels = getEnum('packagechannels')




    new Vue({
        el:"#app",
        data:{
            types:[{type:1,name:"安卓"},{type:2,name:"IOS"},{type:3,name:"PC"},{type:4,name:"ios企业签"}],
            channels:[],
            packagechannels:[],
            detail:{
                id:null,
                game_channel_id:null,
                pack_channel_id:null,
                package_no:null,
                sub_package_no:null,
                type:null,
                description:null,
                channel:"",
                is_test:0,
                configtype:"",
                channelcg:'',
                content:""

            }
        },
        methods:{

            generateChannelPackageNo() {
                console.log('generateChannelPackageNo 被调用', {
                    pack_channel_id: this.detail.pack_channel_id,
                    pack_channel_id_type: typeof this.detail.pack_channel_id,
                    sub_package_no: this.detail.sub_package_no,
                    packagechannels: this.packagechannels
                });
                
                if (this.detail.pack_channel_id && this.detail.sub_package_no) {
                    // 找到选中的母包渠道（尝试多种类型匹配）
                    let selectedChannel = this.packagechannels.find(item => item.id === this.detail.pack_channel_id);
                    
                    // 如果没找到，尝试字符串比较
                    if (!selectedChannel) {
                        selectedChannel = this.packagechannels.find(item => String(item.id) === String(this.detail.pack_channel_id));
                    }
                    
                    // 如果还没找到，尝试数字比较
                    if (!selectedChannel) {
                        selectedChannel = this.packagechannels.find(item => Number(item.id) === Number(this.detail.pack_channel_id));
                    }
                    
                    console.log('选中的母包渠道:', selectedChannel);
                    
                    if (selectedChannel) {
                        // 自动生成：子包号.母包渠道名称
                        const channelName = selectedChannel.nick || selectedChannel.name  || '';
                        const subPackageNoInt = parseInt(this.detail.sub_package_no, 10);
                        const channelNameInt = parseInt(channelName, 10);

                        console.log('渠道名称:', channelName);
                        this.detail.package_no = channelName ? (channelNameInt + subPackageNoInt).toString() : this.detail.sub_package_no;
                    }
                } else if (this.detail.sub_package_no) {
                    const channelName = selectedChannel.nick || selectedChannel.name  || '';

                    // 如果没有选择母包渠道，只显示子包号
                    this.detail.package_no = channelName;
                } else {
                    const channelName = selectedChannel.nick || selectedChannel.name  || '';

                    this.detail.package_no =  channelName;
                }
                
                console.log('最终生成的渠道包号:', this.detail.package_no);
            },
            initWangEditor:function (defaultHtml) {
                const { createEditor, createToolbar } = window.wangEditor;
                const editorConfig = { // 文档地址: https://www.wangeditor.com/v5/menu-config.html#%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%9C%B0%E5%9D%80
                    placeholder: '请输入...',
                    onChange(editor) {
                        const html = editor.getHtml();
                        $('[name=content]').val(html);
                    },
                    MENU_CONF:{
                        uploadImage:{
                            server: '/admin/upload/wangEditor',
                            maxFileSize: 10 * 1024 * 1024, // 10M
                        }
                    }
                };

                const editor = createEditor({
                    selector: '#editor-container',
                    html: defaultHtml,
                    config: editorConfig,
                    mode: 'default' // 'default' or 'simple'
                });

                const toolbarConfig = {};
                const toolbar = createToolbar({
                    editor,
                    selector: '#toolbar-container',
                    config: toolbarConfig,
                    mode: 'default' // or 'simple'
                });
            }
        },

        updated:function(){
          form.render();
        },
        mounted:function(){
            var _this = this;
            
            // 等待 Vue 组件完全渲染后再初始化
            this.$nextTick(function() {
                layui.use(['form','jquery','laytpl'], function () {
                    form = layui.form;
                    var layer = layui.layer ,$ = layui.jquery,laytpl = layui.laytpl;
                    
                    // 加载母包渠道数据
                    _this.packagechannels = packagechannels || [];
                    
                    $.get("/admin/gameChannel/paginate",{page:1,limit:9999},function(res){
                        _this.channels = Array.isArray(res.data) ? res.data : [];
                        console.log('响应数据1:', res.data); // 调试信息
                        console.log('响应数据:', _this.channels); // 调试信息
                        console.log('传入的ID值:', Id); // 调试信息

                        if (Id) { // 编辑操作
                            $.get('/admin/gamePackage/' + Id, {}, function(res) {
                                _this.detail = res.data;
                                console.log('编辑数据:', res.data); // 调试信息
                                
                                _this.detail.sub_package_no = res.data.sub_package_no;

                                _this.detail.pack_channel_id = res.data.packagechannel;
                                _this.detail.package_no = res.data.package_no;
                                
                                // 调试信息
                                console.log('设置的母包渠道ID:', _this.detail.pack_channel_id);
                                console.log('母包渠道数据:', _this.packagechannels);

                                // 确保在数据加载完成后再初始化编辑器和表单
                                _this.$nextTick(function() {
                                    _this.initWangEditor(res.data.content);
                                    // 强制刷新表单，确保选择器显示正确的选中状态
                                    form.render();
                                    // 编辑时也需要生成渠道包号
                                    _this.generateChannelPackageNo();
                                });
                            });
                        } else {
                            // 新增操作，直接初始化空编辑器
                            _this.initWangEditor('');
                        }
                        
                        // 使用 lay-filter 监听渠道ID变化
                        form.on('select(game_channel_id)', function(data) {
                            const selectedChannel = _this.channels.find(item => item.id === Number(data.value));
                            _this.detail.channelcg = selectedChannel ? selectedChannel.id : '';
                            _this.detail.game_channel_id = data.value; // 关键：同步赋值
                            _this.$nextTick(() => {
                                form.render('select'); // 关键：强制刷新 select
                            });
                        });

                        // 使用 lay-filter 监听母包渠道选择变化
                        form.on('select(package_channel_id)', function(data) {
                            console.log('母包渠道选择变化:', data);
                            _this.detail.pack_channel_id = data.value;
                            _this.generateChannelPackageNo();
                        });
                             

                         form.on('select(type)',function(data){
                            _this.detail.type = data.value;
                        });
                        form.on('select(configtype)',function(data){
                            _this.detail.configtype = data.value;
                        });
                        //监听提交
                        form.on('submit(submit)', function (data) {
                            var formData = _this.detail;
                            var editorContent = $('[name=content]').val();
                            formData.content = editorContent;
                            formData.packagechannel=_this.detail.pack_channel_id;
                            if (Id){ //eidt
                                formData._method = 'put';
                                $.post('/admin/gamePackage/'+Id,formData,function(res){
                                    if (res.code===0){
                                        layer.msg('success',{icon:6,time:500},function(){
                                            parent.location.reload();//父页面刷新
                                        });
                                    } else {
                                        layer.msg(res.msg,{icon:5});
                                    }
                                });
                            } else { //add
                                $.post('/admin/gamePackage/add',formData,function(res){
                                    if (res.code===0){
                                        layer.msg('success',{icon:6,time:500},function(){
                                            parent.location.reload();//父页面刷新
                                        });
                                    } else {
                                        layer.msg(res.msg,{icon:5});
                                    }
                                });
                            }

                            return false;
                        });
                        form.on("radio(is_test)",function (data) {
                            _this.detail.is_test = data.value;
                        });
                    });
                });
            });
        }
    });
</script>

</body>
</html>